<?php

//
// *        遍历Admin分组下的Controller
// *        默认所有 private 类 用户都有 权限
// *        主要配置 public 类 用户是否有权限
// *        类注释用 
// *          menu 为菜单名   类菜单为 主菜单  
// *          menuAuto 为默认类文件入口 用于 一级菜单URL配置
namespace Admin\Controller;
use Admin\Controller\AdminController;
use Admin\Model\AuthModel;
/**
 * @author wangnaixin
 * @todo 权限模块 
 */
class AuthController extends AdminController {
    
    public $auth;
    public $roleAuth;
    
    function __construct() {
        parent::__construct();
        $this->auth = new AuthModel();
    }

    /**
     * @author wangnaixin
     * @todo 权限初始化
     * @name 权限初始化
     * @menu 权限初始化
     * @order 120
     */
    public function initAuth(){
        $this->getAllClass($classNames,dirname(__FILE__).'/*');
        foreach ($classNames as $fileName) {
            $className = explode(".class.php", $fileName['name'])[0];
           
            $r = new \ReflectionClass("Admin\\Controller\\".$className);
            
            $classDoc =  $r->getDocComment();
            $classSubName = str_replace(array('Controller','\\'), array('','/'), $className);
            
            if(in_array($classSubName, array('Admin','Upload'))){
                continue;
            }
            
            //存储
            $classInfo = $this->analysisDoc($classDoc);
            if (!$classInfo['todo']) {
                continue;
            }
            $classdata = [
                'controller'=>$classSubName,
                'function'=>'',
                'url'=>"Admin/".$classSubName."/".$classInfo['menuAuto'],
                'todo'=>$classInfo['todo'],
                'isMenu'=> empty($classInfo['menu']) ? 0 : 1,
                'menuName'=>$classInfo['menu'],
                'pid'=>0,
                'order'=>!empty($classInfo['order']) ? $classInfo['order'] : 255,
                'autoCheck'=>$classInfo['autoCheck'],
                'icon'=>$classInfo['icon'],
            ];
            if ($module) {
                $classdata['module'] = $module;
            }
            $classId = $this->auth->saveMenu($classdata);
            
            foreach($r->getMethods(\ReflectionMethod::IS_PUBLIC + \ReflectionMethod::IS_PROTECTED + \ReflectionMethod::IS_PRIVATE) as $v){
                
                if($v->class !== 'Think\Controller' && $v->name !== '__construct'){
                    $doc = $v->getDocComment();
                    if($v->isPrivate() === false){
                        $funInfo = $this->analysisDoc($doc);
                        if (!$funInfo['todo']) {
                            continue;
                        }
                        $funData = [
                            'controller'=>$classSubName,
                            'function'=>$v->name,
                            'pid'=>$classId,
                            'url'=>"Admin/".$classSubName."/".$v->name,
                            'menuName'=>$funInfo['menu'],
                            'todo'=>$funInfo['todo'],
                            'isMenu'=>empty($funInfo['menu']) ? 0 : 1,
                            'order'=>!empty($funInfo['order']) ? $funInfo['order'] : 255
                        ];
                        if ($module) {
                            $funData['module'] = $module;
                        }
                        $this->auth->saveMenu($funData);
                    }
                }
            }
        }
        $this->success("权限/菜单初始化成功!",U('Admin/Index/index'));
    }
    
    /**
     * 
     * @param String $doc 
     * @todo 解析类/方法注释 返回 对应数组
     * @return Array ['author'=>'wangnaixin','menu'=>'权限配置','menuAuto'=>'setAuth','todo'=>'类/方法 描述性文字']
     * 
     */
    private function analysisDoc($doc){
        $doc_arr = explode("@", str_replace("*", "",str_replace("/", "", $doc)));
        $returnData = [
            'author'=>$this->analysisKeyVal('author',$doc_arr),
            'todo'=>$this->analysisKeyVal('todo',$doc_arr),
            'menu'=>$this->analysisKeyVal('menu',$doc_arr),
            'menuAuto'=>$this->analysisKeyVal('menuAuto',$doc_arr),
            'order'=>$this->analysisKeyVal('order',$doc_arr),
            'autoCheck'=>$this->analysisKeyVal('autoCheck',$doc_arr),
            'icon'=>$this->analysisKeyVal('icon',$doc_arr)
        ];
        return $returnData;
    }
    
    /**
     * @todo 根据 key 查找对应值
     * @param String $key 匹配的key
     * @param Array 匹配的数据集
     */
    private function analysisKeyVal($key,$doc){
        $status = false;
        foreach($doc as $v){
            $str = trim($v);
            if(substr($v, 0, strlen($key)) === $key){
                $status = true;
                return trim(str_replace($key, "", $v));
            }
        }
        if($status === false){
            return '';
        }
    }

    private function getAllClass(&$classNames,$path,$subDir='',$suffix='class.php') {
        $files = glob($path);
        foreach ($files as $file) {
            if (is_dir($file) && $file != '.' && $file != '..') {
                $this->getAllClass($classNames,$file.'/*',substr(strrchr($file, '/'),1),$suffix);
            } else if ($file != '.' && $file != '..') {
                $fileName = pathinfo($file,PATHINFO_BASENAME);
                if (strrchr($fileName, $suffix) == $suffix) {
                    $classNames[] = array(
                        'subDir' => $subDir,
                        'name' => $fileName
                    );
                }
            }
        }
    }
    
    
}
